﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO;

namespace LEET.Utilities
{
    public class Helpers
    {
        public delegate T Func<T>();
        public delegate bool Test<T>(T value);
        public static T Poll<T>(Func<T> f, int interval, int timeout, Test<T> test)
        {
            DateTime end = DateTime.Now.AddMilliseconds(timeout);

            T ret = f();
            while (DateTime.Now < end && !test(ret))
            {
                Thread.Sleep(interval);
                ret = f();
            }
            return ret;
        }

        public static T Poll<T>(Func<T> f, int interval, int timeout, T reject)
        {
            return Poll(f, interval, timeout, delegate(T val)
            {
                return !( (reject == null && val == null) || (reject != null && reject.Equals(val)) );
            });
        }

        public static String NormalizeClassName(String name)
        {
            //TODO: remove -+=/ & multiple \s's
            string temp = name.Replace(' ', '_');
            temp = temp.Replace("-", "");
            temp = temp.Replace("/", "");
            temp = temp.Replace("+", "");
            temp = temp.Replace("=", "");
            temp = temp.Replace(".", "");
            return temp;
        }


        public static IEnumerable<FileInfo> FilesFromDir(DirectoryInfo directoryInfo, bool recurse)
        {
            foreach(FileInfo file in directoryInfo.GetFiles())
            {
                yield return file;
            }
            if (recurse)
            {
                foreach (DirectoryInfo dir in directoryInfo.GetDirectories())
                {
                    foreach (FileInfo file in FilesFromDir(dir, true))
                    {
                        yield return file;
                    }
                }
            }
        }

        /// <summary>
        /// Custom join method. Will insert seperator between each element of stuff.
        /// </summary>
        public static String Join<T>(IEnumerable<T> stuff, String seperator)
        {
            StringBuilder buf = new StringBuilder();
            IEnumerator<T> iter = stuff.GetEnumerator();
            if (iter.MoveNext())
            {
                buf.Append(iter.Current.ToString());
                while (iter.MoveNext())
                {
                    buf.Append(seperator).Append(iter.Current.ToString());
                }
            }
            return buf.ToString();
        }

        public static IEnumerable<String> ReadAllLines(TextReader reader)
        {
            String line;
            List<String> list = new List<string>();
            while ((line = reader.ReadLine()) != null)
                list.Add(line);
            return list;
        }
    }
}
